<?php

namespace App\Http\Controllers\Backend\Product;

 
use App\ConstDir\ErrorConst;
use App\Http\Controllers\Backend\BaseController;
use App\Repository\Repositories\Interfaces\AttributesRepository;
use Illuminate\Http\Request;
 
 
class AttributeController extends BaseController
{
    
    protected $attribute_repo;
    
    public function __construct(AttributesRepository $attribute_repo)
    {
        $this->attribute_repo = $attribute_repo;
    }
    
    public function index(Request $request)
    { 
        
        $type = $request->input("type","");
       
        if($type == "all"){
            $attr_values = $this->attribute_repo->all();
            return $this->success(ErrorConst::SUCCESS_CODE, $attr_values,false);
        }else{
            $attr_values = $this->attribute_repo->paginate($this->perPage);
            return $this->success(ErrorConst::SUCCESS_CODE, $attr_values,true);
        }
        
    }
    
    public function show($id)
    {
        $attr_value = $this->attribute_repo->find($id);
        return $this->success(ErrorConst::SUCCESS_CODE, $attr_value);
    }
    
    public function create(Request $request)
    {
        
        $this->validate($request,[
            'name'=> 'required|string|unique:attributes,name',
            'sort'=>'integer',
        ]);
        
        $data = $request->all();
        
        $attr_value = $this->attribute_repo->create($data);
        if($attr_value){
            return $this->success(ErrorConst::SUCCESS_CODE, $attr_value['data']);
        }else{
            return $this->error(ErrorConst::FAILED_CODE);
        }
        
    }
    
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'name'=> 'required|sometimes|string|unique:attributes,name,'.$id,
            'sort'=>'integer',
        ]);
        $data = $request->all();
        
        $ret = $this->attribute_repo->update($data, $id);
        if($ret){
            return $this->success(ErrorConst::SUCCESS_CODE, ErrorConst::SUCCESS_CODE_MSG);
        }else{
            return $this->error(ErrorConst::FAILED_CODE);
        }
    }
    
    public function delete($id)
    {
        $ret = $this->attribute_repo->delete($id);
        
        
        if ($ret) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

   
}
